<?php

namespace app\addons\Command;

use app\cms\community\lib\utils\addons\DiskAddons;
use app\cms\community\lib\utils\addons\exception\addonsEmptyException;
use app\cms\community\lib\utils\addons\lib\saveAddonsAbstract;
use app\cms\model\addons\addonsModel;
use iflow\annotation\utils\CommandAnnotation;
use iflow\console\Adapter\Command;
use iflow\Container\implement\annotation\tools\data\Inject;

#[CommandAnnotation('addons-install')]
class Install extends Command {

    protected string $installType = 'disk';

    protected string $installPath = '';

    protected string $pathType = 'disk';

    protected array $Types = [
        'ns_code' => 'reloadAddonsByNsCode',
        'disk' => 'installAddonsByPath'
    ];

    #[Inject]
    protected addonsModel $addonsModel;

    public function handle(array $event = []) {
        // TODO: Implement handle() method.
        $this->installType = $this->getArgument('-i', $this->installType);
        $this->installPath = $this->getArgument('-p');
        $this->pathType = $this->getArgument('-pt');

        if (!$this->installPath) {
            $this -> Console -> outWrite('插件地址不能为空');
            return true;
        }

        if (empty($this->Types[$this->installType])) {
            $this -> Console -> outWrite('未知安装类型');
            return true;
        }

        $addons = $this -> {$this -> Types[$this -> installType]}($this->installPath);

        if (!$addons instanceof DiskAddons) {
            $this -> Console -> outWrite('插件安装失败');
            return false;
        }

        $save = $addons -> save();

        if ($save) $this -> Console -> outWrite('插件安装成功');

        return $save;
    }

    /**
     * @param string $nsCode
     * @return saveAddonsAbstract|bool
     * @throws addonsEmptyException
     */
    protected function reloadAddonsByNsCode(string $nsCode): saveAddonsAbstract|bool {
        // TODO: 重新安装插件
        $addons = $this->addonsModel -> findInfo([
            'addons_ns_code' => $nsCode
        ]);

        if (!$addons) {
            $this->Console -> outWrite('插件不存在或未安装');
            return false;
        }

        $this->addonsModel -> deleteAddons($nsCode, false);
        $addonsInstall = new DiskAddons(5);
        $addonsInstall -> setAddonsRootPath($addons['addons_install']);
        return $addonsInstall;
    }

    /**
     * @param string $path
     * @return saveAddonsAbstract|bool
     * @throws addonsEmptyException
     */
    protected function installAddonsByPath(string $path): saveAddonsAbstract|bool {
        // TODO: 首次安装插件
        $addons = new DiskAddons(5);
        $isSelf = (bool) $this->getArgument('self', 0);
        if ($isSelf) {
            return $addons -> setAddonsRootPath($path);
        }
        return false;
    }
}